import React, { useEffect, useRef, useState } from 'react'
import { Button, Form, Input, Card, Table, Space, Modal, Checkbox } from 'antd'
import { UserOutlined, DeleteOutlined, FormOutlined } from '@ant-design/icons'
// // 引入发送请求方式
import {
    reqGetPageList,
    reqGetById,
    reqAdd,
    reqUpdate,
    reqGetRoles,
    reqAssignRoles,
    reqRemoveById,
    reqRemoveUsers,
} from '@api/user/index'
export default function User() {
    //   组件挂载的时候发请求
    useEffect(() => {
        getUserList(page, pageSize, searchObj)
    }, [])
    // 封装发请求的方法
    const getUserList = async (page: any, pageSize: any, searchObj: any) => {
        const result = await reqGetPageList(page, pageSize, searchObj)
        setData(result.items)
        setTotal(result.total)
    }
    // form表单方法
    const searchObj = ''
    // 查询
    const onFinish = (values: any) => {
        setPage(1)
        const { username } = values
        getUserList(page, pageSize, username)
    }
    // 清空数据
    const onReset = () => {
        form.resetFields()
        getUserList(page, pageSize, searchObj)
    }


    const [form] = Form.useForm()
    //   table表头数据
    const [columns, setColums] = useState([
        {
            title: '序号',
            key: 'id',
            render: (a: any, b: any, index: any) => {
                return index + 1
            },
        },
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
            render: (text: any) => <a>{text}</a>,
        },
        {
            title: '用户昵称',
            dataIndex: 'nickName',
            key: 'nickName',
        },
        {
            title: '角色列表',
            dataIndex: 'roleName',
            key: 'roleName',
        },
        {
            title: '创建时间',
            dataIndex: 'gmtCreate',
            key: 'gmtCreate',
        },
        {
            title: '更新时间',
            dataIndex: 'gmtModified',
            key: 'gmtModified',
        },
        {
            title: '操作',
            key: 'password',
            render: (_: any, record: any) => (
                <Space size="middle">
                    <Button icon={<UserOutlined />} type="primary" onClick={async () => {
                        setUsername(record.username)
                        const result = await reqGetRoles(record.id)
                        setUserId(record.id)
                        setRole(result.allRolesList.map((item: any) => {
                            return item
                        }))
                        setDefaultCheckedList(result.assignRoles.map((item: any) => {
                            return item.roleName
                        }))
                        setPlainOptions(result.allRolesList.map((item: any) => {
                            return item.roleName
                        }))
                        setIsModalOpen(true);
                    }}></Button>
                    <Button icon={<FormOutlined />} type="primary" onClick={async () => {

                        setId(record.id)
                        const fieldsX = Object.keys(record || '')
                        const fieldsY = Object.values(record || '')
                        const newFields = [] as any
                        fieldsX.map((item: any, index: any) => {
                            newFields.push({
                                name: item,
                                value: fieldsY[index]
                            })
                        })
                        setFields(newFields)
                        setOpen(true)
                    }}></Button>
                    <Button
                        icon={<DeleteOutlined />}
                        type="primary"
                        danger
                        onClick={async () => {
                            const result = await reqRemoveById(record.id)
                            console.log(result);
                            getUserList(page, pageSize, searchObj)

                        }}
                    ></Button>
                </Space>
            ),
        },
    ])
    const [data, setData] = useState([])
    const [ids, setIds] = useState([])
    // 点击多选框的回调
    const rowSelection: any = {
        onChange: async (selectedRowKeys: any, selectedRows: any) => {
            setIds(selectedRowKeys)
            console.log(selectedRowKeys);
        }
    }

    // 分页相关的状态
    const [total, setTotal] = useState<number>(0)
    const [pageSize, setPageSize] = useState<number>(3)
    const [page, setPage] = useState<number>(1)
    // 添加或修改的数据
    const [open, setOpen] = useState(false)
    const [confirmLoading, setConfirmLoading] = useState(false)
    const [addform] = Form.useForm()
    const [fields, setFields] = useState([])
    const [id, setId] = useState('')
    // 存储用户数据
    // const [userData,setUserData] = useState('')

    //   添加或修改用户的dialog展示
    const addOrUpdateUser = () => {
        addform.resetFields()
        setFields([])
        setOpen(true)
    }
    // 添加的卡片回调
    const handleOk = async () => {
        const form = addfromRef.current
        form.validateFields().then(async (values: any) => {
            if (fields.length === 0) {
                const userInfo = addform.getFieldsValue()
                const result = await reqAdd(userInfo)

            } else {
                const userInfo = addform.getFieldsValue()
                const result = await reqGetById(id)

                result.item.username = userInfo.username
                result.item.nickName = userInfo.nickName

                await reqUpdate(result.item)

            }

            setConfirmLoading(true)
            setTimeout(() => {
                setOpen(false)
                setConfirmLoading(false)
            }, 1000)
            getUserList(page, pageSize, searchObj)
        }).catch((errInfo: any) => {

        })
    }
    // 取消按钮 
    const handleCancel = () => {
        setOpen(false)
    }
    // 批量删除按钮
    const removeUsers = async () => {

        const result = await reqRemoveUsers(ids)

    }

    // 分配角色的回调和数据
    const [isModalOpen, setIsModalOpen] = useState(false);
    // 用户名的值
    const [username, setUsername] = useState('')
    const CheckboxGroup = Checkbox.Group;
    // 全部角色
    const [role, setRole] = useState([])
    // 全部的角色的名字
    const [plainOptions, setPlainOptions] = useState([])
    // 用户已有角色名字的数组
    const [defaultCheckedList, setDefaultCheckedList] = useState([])
    // 选中角色的id
    const [userId, setUserId] = useState();
    // 全选框没有全选中的 状态
    const [indeterminate, setIndeterminate] = useState(true);
    // 全选框全选的状态
    const [checkAll, setCheckAll] = useState(false)
    const showModal = () => {
        setIsModalOpen(true);
    };
    // 点击单个复选框的回调
    const onChange = (list: any) => {
        setDefaultCheckedList(list);
        setIndeterminate(!!list.length && list.length < plainOptions.length);
        setCheckAll(list.length === plainOptions.length);
    };
    // 点击全选的回调
    const onCheckAllChange = (e: any) => {
        setDefaultCheckedList(e.target.checked ? plainOptions : []);
        setIndeterminate(false);
        setCheckAll(e.target.checked);
    };
    //   确定按钮
    const handleConfrim = async () => {
        const ids = [] as any
        role.map<any>((item: any) => {
            defaultCheckedList.map<any>(item1 => {
                if (item.roleName == item1) {
                    ids.push(item.id)
                }
            })
        })
        console.log("确定");
        const result = await reqAssignRoles(userId, ids.join(','))
        getUserList(page, pageSize, searchObj)
        setIsModalOpen(false);
    };
    //   取消按钮
    const cancel = () => {
        console.log('取消');

        setIsModalOpen(false);
    };

    const addfromRef = useRef<any>();

    return (
        <Card style={{ margin: 15, borderRadius: 4 }}>
            <Form
                name="form"
                initialValues={{ remember: true }}
                onFinish={onFinish}
                layout="inline"
                autoComplete="off"
                form={form}
            >
                <Form.Item name="username">
                    <Input
                        placeholder="用户名"
                        style={{ width: 180, marginRight: 15 }}
                    />
                </Form.Item>
                <Form.Item>
                    <Button
                        type="primary"
                        htmlType="submit"
                        style={{ marginRight: 15 }}
                    >
                        查询
                    </Button>
                    <Button htmlType="button" onClick={onReset}>
                        清空
                    </Button>
                </Form.Item>
            </Form>
            <div style={{ marginTop: 15, marginRight: 15 }}>
                <Button
                    type="primary"
                    style={{ marginRight: 15 }}
                    onClick={addOrUpdateUser}
                >
                    添加
                </Button>
                <Button type="primary" disabled={ids.length == 0 ? true : false} danger onClick={removeUsers}>
                    批量删除
                </Button>
            </div>

            <Table
                rowKey="id"
                columns={columns}
                dataSource={data}
                style={{ marginTop: 15 }}
                bordered
                rowSelection={rowSelection}
                pagination={{
                    current: page, //current的值为高亮状态
                    total, // 表示要分页的数据总数
                    pageSize, //设置分页时,一页有多少条数据
                    showSizeChanger: true, // 展示选择一页多少数据的下拉框
                    pageSizeOptions: [3, 5, 7], // 控制一页有多少条数据的配置项,和showSizeChanger配合使用
                    showQuickJumper: true, //展示快速跳到指定页的控件
                    // 在分页器前面展示的内容
                    showTotal: function (total) {
                        return `总共：${total}条`
                    },
                    // 点击分页功能，触发onChange函数
                    onChange: function (page: number, pageSize: number) {
                        // 设置每行显示几条数据
                        setPageSize(pageSize)
                        setPage(page)
                        getUserList(page, pageSize, searchObj)
                    },
                }}
            />
            {/* 添加按钮的dialog */}
            <Modal
                title={fields.length == 0 ? "添加用户" : '修改用户'}
                visible={open}
                onOk={handleOk}
                confirmLoading={confirmLoading}
                onCancel={handleCancel}
                width="800px"
                destroyOnClose={true}
            >
                <Form
                    form={addform}
                    fields={fields}
                    ref={addfromRef}
                >
                    <Form.Item label="用户名" labelCol={{ span: 3 }} name="username" rules={[{ required: true }, {
                        validator: (_, value) => {
                            if (value && value.length < 1) {
                                return Promise.reject('用户名称不能为空')
                            } else if (value && (value.length < 4 || value.length > 10)) {
                                return Promise.reject('用户名称必须是4-10位')
                            } else {
                                return Promise.resolve()
                            }
                        }
                    }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="用户昵称" labelCol={{ span: 3 }} name="nickName">
                        <Input />
                    </Form.Item>
                    {
                        fields.length == 0 ? <Form.Item label="用户密码" labelCol={{ span: 3 }} name="password" rules={[{ required: true }, {
                            validator: (_: any, value: any) => {
                                if (value && value.length < 1) {
                                    return Promise.reject('用户密码不能为空')
                                } else if (value && (value.length < 6 || value.length > 10)) {
                                    return Promise.reject('用户密码必须是6-10位')
                                } else {
                                    return Promise.resolve()
                                }
                            }
                        }]}>
                            <Input />
                        </Form.Item> : null
                    }

                </Form>
            </Modal>
            {/* 角色分配按钮的模态框 */}
            <Modal title="角色分配" visible={isModalOpen} onOk={handleConfrim} onCancel={cancel}>
                <Form>
                    <Form.Item label="用户名">
                        <Input value={username} disabled />
                    </Form.Item>
                </Form>
                <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
                    全选
                </Checkbox>
                <CheckboxGroup options={plainOptions} value={defaultCheckedList} onChange={onChange} />
            </Modal>
        </Card>
    )
}
